<template>
	<view>
		<uni-nav-bar dark :fixed="true" shadow bgimage="linear-gradient(to right, #4facfe 0%, #00f2fe 100%)" status-bar
			left-icon="left" left-text="返回" :title="targetUser.userName" @clickLeft="back" />
		<view class="uni-nav-bar-empty-v" id="uni-nav-bar-empty-veiw"></view>
		<view class="message-container">
			<scroll-view ref="content" class="scroll-view" scroll-y="true"
				:style="{height:scrollHeight+'px',scrollTop: scrollTop + 'px'}">
				<graceIMMsg :msgs="graceIMMsgs" :userid="currentUser.userId" :group="groupId"></graceIMMsg>
			</scroll-view>
		</view>
		<view class="content-input-container">
			<image src="https://shangtu.obs.cn-north-4.myhuaweicloud.com/icon/%E5%9B%BE%E7%89%87.png"
				style="width: 60rpx;height: 60rpx;border-radius: 30rpx;" @tap="chooseImage" />
			<view class="grace-im-input">
				<!-- 				<input style="min-height: 80rpx;width: 100%;" cursor-spacing="10" auto-height type="text"
					adjust-position="true" v-model="inputMsg" @blur="endInputText" @focus="startInputText"
					@confirm="sendMessage" /> -->
				<textarea v-model="inputMsg" :maxlength="-1" :auto-height="true" :show-confirm-bar="false"
					:cursor-spacing="5" :fixed="true" :adjust-position="false" @focus="startInputText"
					@blur="endInputText" />
			</view>
			<text class="send-text-msg-v" @tap="sendMessage">发送</text>
		</view>
	</view>
</template>
<script>
	// 引入 IM 组件
	import graceIMInput from "../../graceUI/components/graceIMInput.vue";
	import graceIMMsg from "../../graceUI/components/graceIMMsg.vue";
	import messageApi from "@/api/message.js";
	import imApi from "@/services/ImApi.js";
	import {
		WEBSOCKET_URL,
		PICTURE_BASE_USR
	} from "@/common/common.js";
	import {
		upload
	} from '@/api/api.js';
	// 挂载 vuex
	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		components: {
			graceIMMsg,
			graceIMInput
		},
		data() {
			return {
				currentUser: {
					userId: getApp().globalData.userInfo.userId,
					userName: getApp().globalData.userInfo.userName,
					face: getApp().globalData.userInfo.avatarUrl
				},
				targetUser: {
					userId: '',
					userName: '',
					face: ''
				},
				topEmptyHight: 0,
				ws: null,
				inputMsg: '',
				graceIMMsgs: [],
				scrollHeight: 200,
				barEmptyVeiwHeight: 0,
				inputHeigt: 40,
				keyBoardHeight: 0,
				user: {},
				graceIMToken: '',
				groupId: '',
				graceIMConfig: {},
				buttomInputEmpty: 10,
				graceIMScTop: 0,
				historyLodginText: '点击加载历史消息'
			};
		},
		onReady: function() {
			this.caculateScrollHeight();
			const iMMsgs = uni.getStorageSync('IMMsgs');
			const currentIMMsgs = [];
			const currentGroupId = this.groupId
			// 获取当前会话的聊天记录，并将当前会话中的聊天标记为已读
			for (let i = 0; i < iMMsgs.length; i++) {
				const message = iMMsgs[i];
				if (message.groupId == currentGroupId && message.content != '') {
					message.satus = 1; // 已读
					currentIMMsgs.push(this.convertMsg(message));
				}
			}
			uni.setStorageSync('IMMsgs', iMMsgs);
			this.graceIMMsgs = currentIMMsgs;
		},
		onLoad: function(options) {
			this.groupId = options.groupId;
			this.targetUser.userName = options.userName;
			this.targetUser.userId = options.userId;

			const iMMsgs = uni.getStorageSync('IMMsgs');
			if (this.groupId == null) {
				uni.showLoading({
					title: '创建会话中',
					icon: 'loading'
				});
				imApi.createCoversation(this.currentUser.userId, this.targetUser.userId).then(res => {
					console.log(res)
					this.groupId = res.groupId
					uni.hideLoading();
				})
			}
			this.$wsService.updateMsgRead(options.groupId);
			this.$wsService.swichGroupAndUser(options.groupId, options.userId);
		},
		mounted() {
			this.$wsService.connect(getApp().globalData.userInfo.userId);
			// 监听全局 WebSocketMessage 事件
			uni.$on('WebSocketMessage', this.onWebSocketMessage);
		},
		onUnload() {
			this.$wsService.swichGroupAndUser(null, null);
		},
		methods: {

			back() {
				this.$wsService.swichGroupAndUser(null, null);
				uni.navigateBack({
					delta: 1
				})
			},
			onWebSocketMessage(data) {
				// 处理接收到的 WebSocket 消息
				let meagge = data;
				console.log(meagge)
				if (this.groupId == meagge.groupId && meagge.content != '') {
					this.graceIMMsgs.push(this.convertMsg(meagge));
				}
			},
			convertMsg(msg) {
				let message = {
					uindex: msg.fromUser,
					uname: msg.fromUserName,
					uface: msg.fromUserAvatarUrl,
					content: msg.content,
					contentType: msg.type, // 消息类型 [ 1. 文本类型 2. 图片类型 3. 语音类型 4. 系统通知 ]
					date: msg.createTime,
					group: this.groupId
				}
				return message;
			},
			caculateScrollHeight() {
				const sysInfo = uni.getSystemInfoSync();
				const query = uni.createSelectorQuery().in(this);
				query.select('#uni-nav-bar-empty-veiw').boundingClientRect(data => {
					this.scrollHeight = sysInfo.screenHeight - data.height - 70
				}).exec();
			},
			sendMessage() {
				let message = {
					from: this.currentUser.userId,
					to: this.targetUser.userId,
					groupId: this.groupId,
					content: this.inputMsg,
					action: 'chat',
					type: 'txt'
				}
				this.$wsService.send(message);
				this.inputMsg = ''
			},
			sendPicture(path) {
				let message = {
					from: this.currentUser.userId,
					groupId: this.groupId,
					content: path,
					action: 'chat',
					type: 'img'
				}
				this.$wsService.send(message);
			},
			startInputText(e) {
				console.log("this.scrollHeight", this.scrollHeight)
				console.log(e.detail.height)
				this.keyBoardHeight = e.detail.height
				this.scrollHeight = this.scrollHeight - e.detail.height
				console.log(this.scrollHeight)
			},
			endInputText() {
				this.scrollHeight = this.scrollHeight + this.keyBoardHeight
			},
			chooseImage() {
				uni.chooseImage({
					count: 1, // 默认9，这里限制最多只能选择9张图片
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						console.log(res.tempFilePaths)
						if (res.tempFilePaths[0]) {
							upload(res.tempFilePaths[0]).then(res => {
								console.log(res)
								let path = PICTURE_BASE_USR + res.replace(/"/g, '')
								this.sendPicture(path);
							})
						}

					},
					fail: (err) => {
						// 选择失败后的回调函数
						console.error(err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			}

		}

	}
</script>
<style lang="scss">
	page {
		background: #F6F7F8;
	}

	.content-input-container {
		// transform: translateY(calc(100% - 100rpx));
		padding-top: 5px;
		padding-bottom: 5px;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-wrap: wrap;
		border-top: 2rpx solid #f0f0f0;

		.grace-im-input {
			width: calc(100vw - 250rpx);
			padding: 0 8px;
			background: #f0f0f0;
			border-radius: 5px;
			min-height: 80rpx;
			max-height: 160rpx;
			flex-wrap: nowrap;
			margin-inline: 10px;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-wrap: wrap;

		}

		.send-text-msg-v {
			width: 100rpx;
			height: 60rpx;
			background-color: #3688FF;
			border-radius: 10rpx;
			color: white;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-wrap: wrap;
		}
	}

	.grace-im-msg-list {
		display: flex;
		width: 100%;
		flex: 1;
		margin-bottom: 50px;
	}

	.grace-im-system-msg {
		background: #C1C1C1;
		color: #FFF;
		font-size: 12px;
		line-height: 1.5em;
		padding: 5px 10px;
		display: inline-block;
		border-radius: 3px;
	}
</style>